package com.uu.it.tracker.computation;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class RecordCalculator {
	public String startTime;
	public String finishTime;
	public String date;
	public float distance;
	private float speedIncrement;
	private float maxSpeed;
	private int counter;
	public RecordCalculator(){
		speedIncrement = 0;
		maxSpeed = 0;
		counter = 0;
	}
	
	public void setStartTime() {
		Calendar cal = Calendar.getInstance();
		DateFormat tfmt = DateFormat.getTimeInstance(DateFormat.MEDIUM);
		startTime = tfmt.format(cal.getTime());
	}
	
	public void setFinishTime() {
		Calendar cal = Calendar.getInstance();
		DateFormat tfmt = DateFormat.getTimeInstance(DateFormat.MEDIUM);
		finishTime = tfmt.format(cal.getTime());
	}
	
	public void setDate() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat dfmt = new SimpleDateFormat("dd,MMM,yyyy");
		date = dfmt.format(cal.getTime());
	}
	
	public void incrementSpeed(float speed) {
		if(speed > maxSpeed)
			maxSpeed = speed;
		speedIncrement += speed;
		counter += 1;
	}
	
	/**
	 * get the average Speed, km/h
	 * @return
	 */
	public int avarageSpeed() {
		return (int) (speedIncrement / counter * 3.6 + 0.5);
	}
	
	/**
	 * get the maxSpeed, it is km/h
	 * @return
	 */
	public int maxSpeed() {
		return (int) (maxSpeed*3.6+0.5);
	}
	
	public void computeDistance() {
		//compute duration from finishTime-startTime
		 DateFormat tfmt = DateFormat.getTimeInstance(DateFormat.MEDIUM);
	     Date endtime = null, starttime = null;
	     try {
			endtime = tfmt.parse(finishTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	     try {
			starttime = tfmt.parse(startTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//get the duration of seconds
		//distance km
		long sec = (endtime.getTime()-starttime.getTime())/1000;
		float hour = (float)sec/3600;
       distance = (float)this.avarageSpeed()*hour;
	}
}
